//
//  DelegateTool.swift
//  Intersection
//
//  Created by 好东家 on 2022/8/9.
//

import UIKit
import SwiftUI

@MainActor
public class DelegateTool: NSObject {

// MARK: - 设置window
//    public static func setWindow(window:UIWindow?){
//        let vc = UNNavigationController.init(rootViewController: MainController.init())
//        window?.rootViewController = vc
////        if #available(iOS 13.0, *) {
////            window?.rootViewController = UIHostingController(rootView: MainSwiftUIView())
////        }
//        //设置输出窗口可见
//        window?.makeKeyAndVisible()
//    }
    
}


///
extension UIApplication {

    //声明一个计算属性（注意和懒加载存储属性的区别）
    ///获取window
    @MainActor
    public var currentWindow: UIWindow? {

//        if #available(iOS 13.0, *) {
//            return connectedScenes
//            
//                .filter({$0.activationState == .foregroundActive})
//            
//                .map({$0 as? UIWindowScene})
//            
//                .compactMap({$0})
//            
//                .first?.windows
//            
//                .filter({$0.isKeyWindow}).first
//        } else {
//            return UIApplication.shared.windows.first
//        }
        
        
        if #available(iOS 15.0, *) {
            return UIApplication.shared.connectedScenes
                .filter { $0.activationState == .foregroundActive || $0.activationState == .background }
                .compactMap { $0 as? UIWindowScene }
                .first?.keyWindow
        }else if #available(iOS 13.0, *) {
            // iOS 13-14：通过 connectedScenes 遍历查找 keyWindow
            return UIApplication.shared.connectedScenes
                .filter { $0.activationState == .unattached }
                .compactMap { $0 as? UIWindowScene }
                .flatMap { $0.windows }
                .first { $0.isKeyWindow }
        }else {
            // iOS 12 及以下：直接使用 keyWindow 或 windows.first
            #if swift(>=5.1)
            return UIApplication.shared.keyWindow
            #else
            return UIApplication.shared.windows.first
            #endif
        }

    }

}
